package com.tpc.control.bean;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;



import com.tpc.control.jpa.CommonData;
import com.tpc.control.jpa.CommonDataDAO;
import com.tpc.control.jpa.Con130Report;
import com.tpc.control.jpa.ReserveItem;
import com.tpc.control.jpa.ReserveItemDAO;
import com.tpc.control.jpa.ReserveItemSale;
import com.tpc.control.jpa.ReserveItemSaleDAO;
import com.tpc.control.jpa.SaleData;
import com.tpc.control.jpa.SaleDataDAO;
import com.tpc.control.jpa.SaleDataId;

public class Con130 {

	private String filePDF;
	private boolean printReport = false;
	private String customer_no;
	private String division;
	private Date delivery_date_low,delivery_date_high;
	//private List<ReserveItem> reserveItem = new ArrayList<ReserveItem>();
	//private ReserveItemDAO reserveItemDAO = new ReserveItemDAO();
	private List<Con130Report> report = new ArrayList<Con130Report>();
	//private List<ReserveItemSale> reserveItemSale = new ArrayList<ReserveItemSale>();
	//private ReserveItemSaleDAO reserveItemSaleDAO = new ReserveItemSaleDAO();
	//private List<SaleData> saleData = new ArrayList<SaleData>();
	//private SaleData saleData = new SaleData();
	//private SaleDataDAO saleDataDAO = new SaleDataDAO();
	
	//private List<SaleData> saleData2 = new ArrayList<SaleData>();
	//int a;
	Double orderQuantity = 0.00,quantity;
	Double QuantityValue = 0.00;
	java.text.DecimalFormat dfm = new java.text.DecimalFormat("#,##0.00");
	private WritableCellFormat timesBoldUnderline;
	private WritableCellFormat times;
	private int i,j,k;
	

	
	
	
	public String gotoCon130() {
		customer_no = null;
		division = null;
		delivery_date_low = null;
		delivery_date_high = null;
		report.clear();
		return "con130";
		
	}
	public void showReport2(ActionEvent report2)
	{report.clear();
		if (customer_no.length() == 8) {
			customer_no = "00" + customer_no;
		} else if (customer_no.length() == 9) {
			customer_no = "0" + customer_no;
		}
		ReserveItemDAO reserveItemDAO = new ReserveItemDAO();
		List<ReserveItem> reserveItems = reserveItemDAO.findByCustnoDeliverydateandDivision(this.customer_no, this.division, this.delivery_date_low, this.delivery_date_high);
					int tempOrder = 0;
			for(int a=0;a<reserveItems.size();a++)
			{
				
				ReserveItemSaleDAO reserveItemSaleDAO = new ReserveItemSaleDAO();
				List<ReserveItemSale> reserveItemSales = new ArrayList<ReserveItemSale>();
				CommonDataDAO  commonDataDAO = new CommonDataDAO();
				List<CommonData> commonData = new ArrayList<CommonData>();
				System.out.println(reserveItems.size());
				System.out.println(reserveItems.get(a).getId().getReserveNo());
				System.out.println(reserveItems.get(a).getId().getReserveLine());
				reserveItemSales = reserveItemSaleDAO.findByReNoandReline(reserveItems.get(a).getId().getReserveNo(), reserveItems.get(a).getId().getReserveLine());
		
				for(int d=0;d<reserveItemSales.size();d++){
				try{
					String tempDivision = "";
					Con130Report rep = new Con130Report();
					System.out.println(reserveItemSales.size());//3
					System.out.println(d);
			/*	rep.setSaleOrderNo(reserveItemSales.get(d).getId().getSaleOrder());
					
				rep.setSaleLineItem(reserveItemSales.get(d).getId().getSaleItem());*/
					SaleData saleData = new SaleData();
					SaleDataDAO saleDataDAO = new SaleDataDAO();
					SaleDataId id = new SaleDataId();
					id.setSaleOrder(reserveItemSales.get(d).getId().getSaleOrder());
					System.out.println(reserveItemSales.get(d).getId().getSaleOrder());
					id.setSaleItem(reserveItemSales.get(d).getId().getSaleItem());
					System.out.println(reserveItemSales.get(d).getId().getSaleItem());
					saleData = saleDataDAO.findById(id);
						
					if(!saleData.getCompleteFlag().equals("X"))
					{
						System.out.println(tempDivision);
						System.out.println(reserveItems.get(a).getDivision().toString());
						
						//getdivision
						if(tempDivision.toString()!=reserveItems.get(a).getDivision().toString())
						{
							tempOrder++;
						}
						else{
							tempOrder=1;
						}
						rep.setDivision(reserveItems.get(a).getDivision());
						tempDivision = reserveItems.get(a).getDivision();
						
						
						System.out.println(rep.getDivision());
						//getorderno
						rep.setOrderNo(String.valueOf(tempOrder));
						
						System.out.println(rep.getOrderNo());
						//getsaleorder,getsaledata
						//ไปที่ saledata ดูตัวที่ไม่ใช่ x
						rep.setSaleOrderNo(reserveItemSales.get(d).getId().getSaleOrder());
						System.out.println(rep.getSaleOrderNo());
						rep.setSaleLineItem(reserveItemSales.get(d).getId().getSaleItem());
						System.out.println(rep.getSaleLineItem());
		
				
					commonData = commonDataDAO.findBySaleOrderAndSaleItem(reserveItemSales.get(d).getId().getSaleOrder(), reserveItemSales.get(d).getId().getSaleItem());
				
				//find remark.
				System.out.println(commonData.size());
				for(int c=0;c<commonData.size();c++){
					System.out.println(commonData.get(c).getReserveDyeRemark());
					if(commonData.get(c).getReserveDyeRemark() != null){
						rep.setRemark(commonData.get(c).getReserveDyeRemark());
						System.out.println(rep.getRemark());
						break;
					}	
				}
					
					
					}if(rep.getDivision()!=null)
					{
						report.add(rep);
						//rep = null;
						}
				}catch(Exception ex1){
					ex1.printStackTrace();
				}
				}
			
				tempOrder =0;
			}
			
	}
	public void showReport1(ActionEvent rep)
	{	report.clear();
		if (customer_no.length() == 8) {
			customer_no = "00" + customer_no;
		} else if (customer_no.length() == 9) {
			customer_no = "0" + customer_no;
		}
		search();
	}
	
	private void search(){
		
		ReserveItemDAO reserveItemDAO = new ReserveItemDAO();
		//List<ReserveItem> reserveItems = reserveItemDAO.findByCustnoDeliverydateandDivision(this.customer_no, this.division, this.delivery_date_low, this.delivery_date_high);
		List<String> reserveItems2 = reserveItemDAO.findDistinctDivision(this.customer_no, this.division, this.delivery_date_low, this.delivery_date_high);
		System.out.println(reserveItems2.size());
		
		//loop Division เพื่อหาปริมาณที่จองของแต่ละ Division.
			
		
		for(int a=0;a<reserveItems2.size();a++){
		//	ReserveItem rItem = reserveItems2.get(a);
			Con130Report rep = new Con130Report();
			SaleData saleData = new SaleData();
			rep.setDivision(reserveItems2.get(a)); //เก็บค่า Division ช่องที่ 1
			rep.setReserveQty(dfm.format(reserveItemDAO.findSumQuantity(reserveItems2.get(a)))); //เก็บค่าปริมาณที่จอง ตามแต่ละ Division
			
			List<ReserveItem> temp = getDataByDivision(rep.getDivision());
			
			Object []sale = new Object[7];
			//System.out.println(getPriceValue(temp)[0].toString());
			sale = getPriceValue(temp);
			
			rep.setReserveValue(sale[0].toString());//เก็บค่ามูลค่าที่จอง
			rep.setOrderQty(sale[1].toString());
			rep.setOrderAmount(sale[2].toString());
			rep.setCompleteFlag(sale[3].toString());
			rep.setCompleteAmount(sale[4].toString());
			rep.setNoCompleteFlag(sale[5].toString());
			rep.setNoCompleteAmount(sale[6].toString());
			//getSaleDataQuantityVolume(temp);//ปริมาณที่เปิด Order
			//getPriceValue(getDataByDivision(rep.getDivision()));
		
			/*rep.setOrderQty(null);
			rep.setOrderCompleteQty(null);
			rep.setOrderCompleteValue(null);
			rep.setOrderQtyRemain(null);
			rep.setOrderQtyValue(null);
			rep.setOrderQtyDetail(null);
			rep.setOrderNo(null);
			rep.setSaleOrderNo(null);
			rep.setSaleLineItem(null);
			rep.setRemark(null);*/
			report.add(rep);
		}
/*			for(int z=0;z<report.size();z++)
			{
				System.out.println(report.get(z).getDivision());
			}*/
	}

	public void back(ActionEvent a){
		customer_no = null;
		division = null;
		delivery_date_low = null;
		delivery_date_high = null;
		report.clear();
		
	}
	
	public List<ReserveItem> getDataByDivision(String division){
			ReserveItemDAO reserveItemDAO = new ReserveItemDAO(); 
			List<ReserveItem> reserveItem = reserveItemDAO.findByDivision(division);

			return reserveItem;
	}
	public Object[] getPriceValue(List<ReserveItem> reserveItem){
		//Double Price= 0.0d;
		ReserveItemSaleDAO reserveItemSaleDAO = new ReserveItemSaleDAO();
		List<ReserveItemSale> reserveItemSale = new ArrayList<ReserveItemSale>(); 
		Double sum=0.0; // มูลค่าที่จอง คือนำค่า sum ตามแผนกของแต่ละใบจอง iem มา คูณกับ ค่าแรกของ price ใน saledata
		Double sumQuantity=0.0d;  // ทำปริมาณที่เปิด Order 
		Double sumOrderAmount=0.0d; // มูลค่าที่เปิด Order
		int completeFlag = 0;// จำนวน Order ที่ complete 
		Double sumCompleteAmount=0.0d;
		int noCompleteFlag = 0;
		Double sumNoCompleteAmount =0.0d;
		
		//System.out.println(reserveItem.size());
		for(int x=0;x<reserveItem.size();x++){
			SaleDataDAO saleDataDAO = new SaleDataDAO();
			SaleData saleData = new SaleData();
		try{
			
			//System.out.println(reserveItem.get(x).getId().getReserveNo());
			//System.out.println( reserveItem.get(x).getId().getReserveLine());
			////////////
			List<ReserveItemSale> temp = reserveItemSaleDAO.findByReNoandReline(reserveItem.get(x).getId().getReserveNo(), reserveItem.get(x).getId().getReserveLine());		
			
			System.out.println(temp.size());
			/////////////
			for(int y=0;y<temp.size();y++){
			saleData = saleDataDAO.findBySaleOrderAndSaleItem(temp.get(y).getId().getSaleOrder(), temp.get(y).getId().getSaleItem()) ;
			
			
			Double price = saleData.getPrice();
			
			Double quantity = saleData.getQuantity();
			Double orderValue = saleData.getOrderAmount();
			String comFlag = saleData.getCompleteFlag();
			Double flagAmount = saleData.getCompleteAmount();
			Double noFlagAmount = saleData.getRemainAmount();
			
		//	System.out.println(y);
			///////////////////////////////////
			if(y==0){
			 sum += price*reserveItem.get(x).getReserveQty();
			}
			// System.out.println(sumQuantity);
			// System.out.println(quantity);
			 sumQuantity += quantity;
			 sumOrderAmount += orderValue;
			// System.out.println(sumQuantity);
			 if(!comFlag.equals(""))
			 {
				 completeFlag +=1;
				 sumCompleteAmount += flagAmount;
			 }else{
				 noCompleteFlag +=1;
				 sumNoCompleteAmount += noFlagAmount;
			 }
			 
			// System.out.println(sum);
			// System.out.println(sumQuantity);
			// System.out.println(completeFlag);
		}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		}
		Object[] Object = new Object[7];
		Object[0]  = dfm.format(sum);
		Object[1] = dfm.format(sumQuantity);
		Object[2] = dfm.format(sumOrderAmount);
		Object[3] = completeFlag;
		Object[4] = dfm.format(sumCompleteAmount);
		Object[5] = noCompleteFlag;
		Object[6] = dfm.format(sumNoCompleteAmount);
		
		return Object;
	}
/*	public void getSaleDataQuantityVolume(List<ReserveItem> reserveItem){
		SaleDataDAO saleDataDAO = new SaleDataDAO();
		for(int x=0;x<reserveItem.size();x++){
		Double sumQuantity = saleDataDAO.findQuantityByOrderAndItem(reserveItem.get(x).getId().get, propertyName2)
		}
		}*/
	public String getCustomer_no() {
		return customer_no;
	}
	public void setCustomer_no(String customer_no) {
		this.customer_no = customer_no;
	}
	public String getDivision() {
		return division;
	}
	public void setDivision(String division) {
		this.division = division;
	}

	public Date getDelivery_date_low() {
		return delivery_date_low;
	}

	public void setDelivery_date_low(Date delivery_date_low) {
		this.delivery_date_low = delivery_date_low;
	}

	public Date getDelivery_date_high() {
		return delivery_date_high;
	}

	public void setDelivery_date_high(Date delivery_date_high) {
		this.delivery_date_high = delivery_date_high;
	}

	public List<Con130Report> getReport() {
		return report;
	}

	public void setReport(List<Con130Report> report) {
		this.report = report;
	}

	public void operate(ActionEvent a) throws WriteException, IOException{
		write();
	}
	///////////////////////////////////////Excel 132/////////////////////////////
	
	public void write() throws IOException, WriteException {

		javax.faces.context.FacesContext conText = javax.faces.context.FacesContext
				.getCurrentInstance();
		javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) conText
				.getExternalContext().getResponse();

		/*
		 * HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet1 =
		 * wb.createSheet("Summary"); sheet1.createFreezePane(1, 11); CellStyle
		 * styleAmount = wb.createCellStyle(); DataFormat format =
		 * wb.createDataFormat();
		 * styleAmount.setDataFormat(format.getFormat("#,##0.00"));
		 */

		//File file = new File(inputFile);
		WorkbookSettings wbSettings = new WorkbookSettings();

		wbSettings.setLocale(new Locale("en", "EN"));

		WritableWorkbook workbook = Workbook.createWorkbook(response
				.getOutputStream());
		workbook.createSheet("Report", 0);
		WritableSheet excelSheet = workbook.getSheet(0);
		createLabel(excelSheet);
		createContent(excelSheet);
		
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition",
				"attachment; filename=con132_summary.xls");
		javax.servlet.ServletOutputStream out = response.getOutputStream();

		/* wb.write(out); */
		workbook.write();
		workbook.close();

		try {
			conText.getApplication().getStateManager().saveSerializedView(
					conText);
			conText.responseComplete();
			// Process p =
			// Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:/temp/excel.xls");
			// p.waitFor();

			System.out.println("Done");

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private void createLabel(WritableSheet sheet) throws WriteException {
		// Lets create a times font
		WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
		// Define the cell format
		times = new WritableCellFormat(times10pt);
		// Lets automatically wrap the cells
		times.setWrap(true);

		// Create create a bold font with unterlines
		WritableFont times10ptBoldUnderline = new WritableFont(
				WritableFont.TIMES, 10, WritableFont.BOLD, false,
				UnderlineStyle.SINGLE);
		timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
		// Lets automatically wrap the cells
		timesBoldUnderline.setWrap(true);

		CellView cv = new CellView();
		cv.setFormat(times);
		cv.setFormat(timesBoldUnderline);
		cv.setAutosize(true);
		try {
			sheet.mergeCells(1, 0, 3, 0);
		} catch (Exception x) {
			System.out.println(x);
			System.out.println("merge fail");
		}
		// Write a few headers
		addCaption(sheet, 1, 0, "รายงานสรุปรายละเอียด Order ค้า่งส่ง");
		addCaption(sheet, 0, 1, "แผนก");
		addCaption(sheet, 1, 1, "ลำดับที่");
		addCaption(sheet, 2, 1, "Sale Order No.");
		addCaption(sheet, 3, 1, "Sale Line Item");
		addCaption(sheet, 4, 1, "หมายเหตุ");
	/*	addCaption(sheet, 5, 1, "สถานะใบจอง");
		addCaption(sheet, 6, 1, "วันที่สร้างใบจอง");
		addCaption(sheet, 7, 1, "รหัส Com");
		addCaption(sheet, 8, 1, "รหัส Design");
		addCaption(sheet, 9, 1, "ปริมาณที่จอง");
		addCaption(sheet, 10, 1, "หน่วย");
		addCaption(sheet, 11, 1, "กำหนดส่ง");
		addCaption(sheet, 12, 1, "วันที่นัดวัตถุดิบเข้า");
		addCaption(sheet, 13, 1, "วันที่วัตถุดิบเข้าจริง");
		addCaption(sheet, 14, 1, "วันที่เริ่มผลิตเกรย์ตามแผน");
		addCaption(sheet, 15, 1, "วันที่ผลิตเกรย์เสร็จตามแผน");
		addCaption(sheet, 16, 1, "วันที่เริ่มย้อม / ผลิตสินค้าตามแผน");
		addCaption(sheet, 17, 1, "วันที่ย้อม / ผลิตสินค้าเสร็จตามแผน");*/
		cv.setAutosize(true);
	}

	private void createContent(WritableSheet sheet) throws WriteException,
			RowsExceededException {

		// data
		int j = 0;
		for (int i = 2; i < report.size() + 2; i++) {

			// First column
			addLabel(sheet, 0, i, report.get(j).getDivision());
			// Second column
			addLabel(sheet, 1, i, report.get(j).getOrderNo());
			addLabel(sheet, 2, i, report.get(j).getSaleOrderNo());
			addLabel(sheet, 3, i, report.get(j).getSaleLineItem());
			addLabel(sheet, 4, i, report.get(j).getRemark());
/*			addLabel(sheet, 5, i, report.get(j).getStatus().toString());
			addLabel(sheet, 6, i, report.get(j).getCreateDate());
			addLabel(sheet, 7, i, report.get(j).getMaterialNo());
			addLabel(sheet, 8, i, report.get(j).getMaterialDesign());
			addLabel(sheet, 9, i, report.get(j).getReserveQty().toString());
			addLabel(sheet, 10, i, report.get(j).getUom());*/

			/*
			 * System.out.println(df.format(reserveitem.get(i).getDeliveryDate())
			 * ); System.out.println(i);
			 */

/*			addLabel(sheet, 11, i, report.get(j).getDeliveryDate());
			addLabel(sheet, 12, i, report.get(j).getReceiveRawMaterialPlan());
			addLabel(sheet, 13, i, report.get(j).getReceiveRawMaterialActual());
			addLabel(sheet, 14, i, report.get(j).getGreigeStartPlan());
			addLabel(sheet, 15, i, report.get(j).getGreigeFinishPlan());
			addLabel(sheet, 16, i, report.get(j).getDyeingStartPlan());
			addLabel(sheet, 17, i, report.get(j).getDyeingFinishPlan());*/
			j++;
			
			sheet.setColumnView(0, 6);
			sheet.setColumnView(1, 12);
			sheet.setColumnView(2, 12);
			sheet.setColumnView(3, 12);
			sheet.setColumnView(4, 12);
		
		}
		System.out.println("Test");
	}

	private void addCaption(WritableSheet sheet, int column, int row, String s)
			throws RowsExceededException, WriteException {
		Label label;
		label = new Label(column, row, s, timesBoldUnderline);
		sheet.addCell(label);
	}

	private void addNumber(WritableSheet sheet, int column, int row,
			Integer integer) throws WriteException, RowsExceededException {
		Number number;
		number = new Number(column, row, integer, times);
		sheet.addCell(number);
	}

	private void addLabel(WritableSheet sheet, int column, int row, String s)
			throws WriteException, RowsExceededException {
		Label label;
		label = new Label(column, row, s, times);
		sheet.addCell(label);
	}
	
	
////////////////////////////////////////End of Excel 132//////////////////////
	
	//Excel131
	public void operate2(ActionEvent a) throws WriteException, IOException{
		write2();
	}
	
	public void write2() throws IOException, WriteException {

		javax.faces.context.FacesContext conText = javax.faces.context.FacesContext
				.getCurrentInstance();
		javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) conText
				.getExternalContext().getResponse();

		/*
		 * HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet1 =
		 * wb.createSheet("Summary"); sheet1.createFreezePane(1, 11); CellStyle
		 * styleAmount = wb.createCellStyle(); DataFormat format =
		 * wb.createDataFormat();
		 * styleAmount.setDataFormat(format.getFormat("#,##0.00"));
		 */

		//File file = new File(inputFile);
		WorkbookSettings wbSettings = new WorkbookSettings();

		wbSettings.setLocale(new Locale("en", "EN"));

		WritableWorkbook workbook = Workbook.createWorkbook(response
				.getOutputStream());
		workbook.createSheet("Report", 0);
		WritableSheet excelSheet = workbook.getSheet(0);
		createLabel2(excelSheet);
		createContent2(excelSheet);

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition",
				"attachment; filename=con131_summary.xls");
		javax.servlet.ServletOutputStream out = response.getOutputStream();

		/* wb.write(out); */
		workbook.write();
		workbook.close();

		try {
			conText.getApplication().getStateManager().saveSerializedView(
					conText);
			conText.responseComplete();
			// Process p =
			// Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:/temp/excel.xls");
			// p.waitFor();

			System.out.println("Done");

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private void createLabel2(WritableSheet sheet) throws WriteException {
		// Lets create a times font
		WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
		// Define the cell format
		times = new WritableCellFormat(times10pt);
		// Lets automatically wrap the cells
		times.setWrap(true);

		// Create create a bold font with unterlines
		WritableFont times10ptBoldUnderline = new WritableFont(
				WritableFont.TIMES, 10, WritableFont.BOLD, false,
				UnderlineStyle.SINGLE);
		timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
		// Lets automatically wrap the cells
		timesBoldUnderline.setWrap(true);

		CellView cv = new CellView();
		cv.setFormat(times);
		cv.setFormat(timesBoldUnderline);
		cv.setAutosize(true);
		try {
			sheet.mergeCells(3, 0, 5, 0);
		} catch (Exception x) {
			System.out.println(x);
			System.out.println("merge fail");
		}
		// Write a few headers
		addCaption2(sheet, 3, 0, "รายงานสรุปข้อมูลใบจองสำหรับผู้บริหาร");
		addCaption2(sheet, 0, 1, "แผนก");
		addCaption2(sheet, 1, 1, "ปริมาณที่จอง");
		addCaption2(sheet, 2, 1, "มูลค่าที่จอง");
		addCaption2(sheet, 3, 1, "ปริมาณที่เปิด Order");
		addCaption2(sheet, 4, 1, "มูลค่าที่เปิด Order");
		addCaption2(sheet, 5, 1, "จำนวน Order ที่ Complete");
		addCaption2(sheet, 6, 1, "มูลค่า Order ที่ Complete");
		addCaption2(sheet, 7, 1, "จำนวน Order คงค้าง");
		addCaption2(sheet, 8, 1, "มูลค่า Order คงค้าง");


		
	}

	private void createContent2(WritableSheet sheet) throws WriteException,
			RowsExceededException {

		// data
		int j = 0;
		for (int i = 2; i < report.size() + 2; i++) {

			// First column
			addLabel2(sheet, 0, i, report.get(j).getDivision());
			// Second column
			addLabel2(sheet, 1, i, report.get(j).getReserveQty().toString());
			addLabel2(sheet, 2, i, report.get(j).getReserveValue());
			addLabel2(sheet, 3, i, report.get(j).getOrderQty());
			addLabel2(sheet, 4, i, report.get(j).getOrderAmount());
			addLabel2(sheet, 5, i, report.get(j).getCompleteFlag());
			addLabel2(sheet, 6, i, report.get(j).getCompleteAmount());
			addLabel2(sheet, 7, i, report.get(j).getNoCompleteFlag());
			addLabel2(sheet, 8, i, report.get(j).getNoCompleteAmount());


			/*
			 * System.out.println(df.format(reserveitem.get(i).getDeliveryDate())
			 * ); System.out.println(i);
			 */

/*			addLabel(sheet, 11, i, report.get(j).getDeliveryDate());
			addLabel(sheet, 12, i, report.get(j).getReceiveRawMaterialPlan());
			addLabel(sheet, 13, i, report.get(j).getReceiveRawMaterialActual());
			addLabel(sheet, 14, i, report.get(j).getGreigeStartPlan());
			addLabel(sheet, 15, i, report.get(j).getGreigeFinishPlan());
			addLabel(sheet, 16, i, report.get(j).getDyeingStartPlan());
			addLabel(sheet, 17, i, report.get(j).getDyeingFinishPlan());*/
			j++;
		
		}
		sheet.setColumnView(0, 6);
		sheet.setColumnView(1, 12);
		sheet.setColumnView(2, 12);
		sheet.setColumnView(3, 12);
		sheet.setColumnView(4, 12);
		sheet.setColumnView(5, 15);
		sheet.setColumnView(6, 12);
		sheet.setColumnView(7, 15);
		sheet.setColumnView(8, 12);
		System.out.println("Test");
	}

	private void addCaption2(WritableSheet sheet, int column, int row, String s)
			throws RowsExceededException, WriteException {
		Label label;
		label = new Label(column, row, s, timesBoldUnderline);
		sheet.addCell(label);
	}

	private void addNumber2(WritableSheet sheet, int column, int row,
			Integer integer) throws WriteException, RowsExceededException {
		Number number;
		number = new Number(column, row, integer, times);
		sheet.addCell(number);
	}

	private void addLabel2(WritableSheet sheet, int column, int row, String s)
			throws WriteException, RowsExceededException {
		Label label;
		label = new Label(column, row, s, times);
		sheet.addCell(label);
	}
	//End of Excel131
	
	
	
/*	public JRDataSource create(JasperReport arg0) throws JRException {
		
	}*/
	
/*	public void dispose(JRDataSource arg0) throws JRException {
		// TODO Auto-generated method stub

	}*/
	/*public void openPDF()throws IOException, WriteException{
		
		javax.faces.context.FacesContext conText = javax.faces.context.FacesContext
		.getCurrentInstance();
javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) conText
		.getExternalContext().getResponse();
		
		
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition",
				"attachment; filename=con132_summary.pdf");
		javax.servlet.ServletOutputStream out = response.getOutputStream();
		
		try {
			conText.getApplication().getStateManager().saveSerializedView(
					conText);
			conText.responseComplete();
			// Process p =
			// Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:/temp/excel.xls");
			// p.waitFor();

			System.out.println("Done");

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}*/
	/////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
/*public void printFormEvent() {
		
		
		javax.faces.context.FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
		
		HttpServletRequest request = (HttpServletRequest)
		context.getExternalContext().getRequest();
		String classpath =
		(String)request.getSession(true).getServletContext().getAttribute("org.apache.catalina.jsp_classpath");
		System.setProperty("jasper.reports.compile.class.path", classpath);

		String sReportPath = System.getProperty("catalina.base") + "/webapps/" + context.getExternalContext().getRequestContextPath() + "/report/Con132Report.jrxml";
		try {
		JasperReport jasperReport = JasperCompileManager.compileReport(sReportPath);
		JasperPrint jasperPrint=null;

			JRAbstractBeanDataSourceProvider dsf
			   = (JRAbstractBeanDataSourceProvider)Class.forName("com.tpc.control.bean.Con132Report").newInstance();
		
		JRAbstractBeanDataSourceProvider dsf
		   = (JRAbstractBeanDataSourceProvider)Class.forName("com.tpc.control.bean.Con130").newInstance();
			JRBeanCollectionDataSource ds = (JRBeanCollectionDataSource)dsf.create(jasperReport);               
			 if (ds != null) {
			   jasperPrint = JasperFillManager.fillReport(jasperReport, null, ds);
			 }
		//Stream output to PDF file
		 javax.faces.context.FacesContext conText = javax.faces.context.FacesContext
			.getCurrentInstance();
		 javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) conText
			.getExternalContext().getResponse();
		 
		 filePDF =   "Con132" + FunctionUtil.getDateTime() + ".pdf";
 old version pip
		 String fileName = ((ServletContext)context.getExternalContext().getContext()).getRealPath("/")  + filePDF;
		 System.out.println(fileName);
		 FileOutputStream flt = new FileOutputStream(new File(fileName));
		 

		 JRExporter exporter = new JRPdfExporter();//PDF Export  
		 exporter.setParameter( JRExporterParameter.JASPER_PRINT, jasperPrint );
		 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, flt);
		
		 exporter.exportReport();
		 flt.close();
		 
		 InputStream stream = new FileInputStream(fileName);
		 byte[] byteArray = FunctionUtil.toByteArray(stream);
	        //resource = new MyResource(byteArray);    
	        printReport = true;
		
		 
		 
//	************ new **************
	
	response.setContentType("application/pdf");
	response.setHeader (
		    "Content-Disposition", "attachment;filename=\""+filePDF+"\"");
	
	ServletOutputStream sosStream = response.getOutputStream();
	
	JRExporter exporter = new JRPdfExporter();// PDF Export
	exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
	exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, sosStream);
//	exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "../FSReport.pdf");
	// Set Stream header

//	System.out.println("Exporting report...");
//	exporter.exportReport();
//	System.out.println("Done!");

	 exporter.exportReport();
	 sosStream.flush();
	 context.responseComplete();
		 
		 
		} catch (Exception e) {
			e.printStackTrace();
			
			
		}
		
	}*/

}
